// 导出所有状态管理相关内容
export * from './authStore';
export * from './appStore';
export * from './dataStore';

// 重新导出主要钩子供便捷使用
export { useAuth } from './authStore';
export { 
  useAppUI, 
  useAppNotifications, 
  useAppSearch, 
  useAppModals 
} from './appStore';
export { useDataStore } from './dataStore';

// 类型定义
export interface StoreState {
  auth: ReturnType<typeof import('./authStore').useAuthStore.getState>;
  app: ReturnType<typeof import('./appStore').useAppStore.getState>;
  data: ReturnType<typeof import('./dataStore').useDataStore.getState>;
}

// 存储重置函数
export const resetAllStores = () => {
  const { useAuthStore } = require('./authStore');
  const { useAppStore } = require('./appStore');
  const { useDataStore } = require('./dataStore');
  
  // 重置认证状态
  useAuthStore.getState().logout();
  
  // 重置应用状态
  useAppStore.setState({
    sidebarOpen: true,
    sidebarCollapsed: false,
    loading: false,
    notifications: [],
    toasts: [],
    unreadNotificationCount: 0,
    globalSearchOpen: false,
    searchQuery: '',
    searchResults: [],
    searchLoading: false,
    modals: {},
  });
  
  // 重置数据缓存
  useDataStore.getState().clearCache();
};

// 存储初始化函数
export const initializeStores = async () => {
  try {
    // 简化初始化过程，只做基本设置
    console.log('初始化存储...');
    
    // 不需要这里检查认证，让组件自己处理
    
  } catch (error) {
    // 不抛出错误，只记录日志
    console.warn('初始化存储警告:', error);
  }
};

// 存储持久化配置
export const persistConfig = {
  auth: {
    name: 'auth-storage',
    partialize: (state: any) => ({
      user: state.user,
      currentTenant: state.currentTenant,
      currentOrganization: state.currentOrganization,
      permissions: state.permissions,
      token: state.token,
      refreshToken: state.refreshToken,
      isAuthenticated: state.isAuthenticated,
    }),
  },
  app: {
    name: 'app-storage',
    partialize: (state: any) => ({
      theme: state.theme,
      sidebarCollapsed: state.sidebarCollapsed,
    }),
  },
  data: {
    name: 'data-storage',
    partialize: (state: any) => ({
      // 不持久化数据，保持数据的实时性
    }),
  },
};

// 存储调试工具
export const storeDevtools = {
  name: 'Multi-Tenant Admin System',
  trace: true,
  traceLimit: 25,
};

// 存储监听器
export const setupStoreListeners = () => {
  const { useAuthStore } = require('./authStore');
  const { useAppStore } = require('./appStore');
  const { useDataStore } = require('./dataStore');
  
  // 监听认证状态变化
  useAuthStore.subscribe(
    (state) => state.isAuthenticated,
    (isAuthenticated, previousIsAuthenticated) => {
      if (!isAuthenticated && previousIsAuthenticated) {
        // 用户登出时清理数据
        useDataStore.getState().clearCache();
        useAppStore.getState().clearNotifications();
        useAppStore.getState().clearToasts();
      }
    }
  );
  
  // 监听租户切换
  useAuthStore.subscribe(
    (state) => state.currentTenant?.id,
    (currentTenantId, previousTenantId) => {
      if (currentTenantId && currentTenantId !== previousTenantId) {
        // 租户切换时重新加载相关数据
        const dataStore = useDataStore.getState();
        dataStore.refreshOrganizations(currentTenantId);
        dataStore.refreshRoles(currentTenantId);
      }
    }
  );
  
  // 监听组织切换
  useAuthStore.subscribe(
    (state) => state.currentOrganization?.id,
    (currentOrganizationId, previousOrganizationId) => {
      if (currentOrganizationId && currentOrganizationId !== previousOrganizationId) {
        // 组织切换时重新加载相关数据
        const dataStore = useDataStore.getState();
        dataStore.refreshDepartments(currentOrganizationId);
        dataStore.refreshUsers({ organizationId: currentOrganizationId });
      }
    }
  );
  
  // 监听错误状态
  useDataStore.subscribe(
    (state) => state.errors,
    (errors) => {
      const appStore = useAppStore.getState();
      
      // 将数据错误转换为通知
      Object.entries(errors).forEach(([key, error]) => {
        if (error) {
          appStore.showToast({
            type: 'error',
            title: '数据加载失败',
            message: `${key}: ${error}`,
            duration: 5000,
          });
        }
      });
    }
  );
};

// 存储性能监控
export const storePerformanceMonitor = {
  // 监控存储更新频率
  updateCounts: {
    auth: 0,
    app: 0,
    data: 0,
  },
  
  // 记录更新
  recordUpdate: (storeName: keyof typeof storePerformanceMonitor.updateCounts) => {
    storePerformanceMonitor.updateCounts[storeName]++;
  },
  
  // 获取统计信息
  getStats: () => ({
    ...storePerformanceMonitor.updateCounts,
    timestamp: new Date().toISOString(),
  }),
  
  // 重置统计
  reset: () => {
    storePerformanceMonitor.updateCounts = {
      auth: 0,
      app: 0,
      data: 0,
    };
  },
};